package com.yifushidai.service;

import com.yifushidai.entity.ApiUniqueMac;
import com.yifushidai.entity.KeypassBandEntity;
import com.yifushidai.mapper.ApiUniqueMacMapper;
import com.yifushidai.mapper.KeypassBandEntityMapper;
import com.yifushidai.mapper.OptDeviceLogMapper;
import com.yifushidai.utils.ErrorCodeEnum;
import com.yifushidai.utils.R;
import com.yifushidai.utils.ShisuMinaPushUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class KeyPassService {
    @Autowired
    private ApiUniqueMacMapper apiUniqueMacMapper;
    @Autowired
    private KeypassBandEntityMapper keyPassMapper;
    @Autowired
    private OptDeviceLogMapper optDeviceLogMapper;

    public R getFinalKey(String mac) {
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(mac).build());
        if (null == one) return R.error(ErrorCodeEnum.MAC_NULL);

        KeypassBandEntity keypassEntity = keyPassMapper.queryByMac(mac);
        if (keypassEntity == null) {
            return R.error(ErrorCodeEnum.DATA_NULL);
        }
        return R.ok().put(keypassEntity.getKeypass());
    }

    public R modFinalKey(String mac, String newKey, HttpServletRequest request) throws InterruptedException {
        if (!newKey.matches("^\\w{6}$")) {
            return R.error(ErrorCodeEnum.ARGUMENT_VALIDATION);
        }
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(mac).build());
        if (null == one) return R.error(ErrorCodeEnum.MAC_NULL);

        KeypassBandEntity keypassEntity = keyPassMapper.queryByMac(mac);
        if (keypassEntity == null) return R.error(ErrorCodeEnum.DATA_NULL);

        String prefix = "修改固定密码";
        Object res = ShisuMinaPushUtils.push(mac, "finalKey:" + newKey);
        if ("OK".equals(res)) {
            keypassEntity.setKeypass(newKey);
            if (keyPassMapper.updateByPrimaryKeySelective(keypassEntity) > 0) {
                return R.ok().put(keypassEntity);
            } else {
                return R.error(ErrorCodeEnum.DATASOURCE_ERROR);
            }
        } else {
            return R.error(ErrorCodeEnum.MINA_PUSH_ERROR);
        }
    }

    public R initPwd(String mac, String pwdType, HttpServletRequest request) throws InterruptedException {
        if (!pwdType.matches("^\\w{2}$")) {
            return R.error(ErrorCodeEnum.ARGUMENT_VALIDATION);
        }
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(mac).build());
        if (null == one) return R.error(ErrorCodeEnum.MAC_NULL);

        String prefix = "初始化指纹管理密码";
        Object res = ShisuMinaPushUtils.push(mac, "initPwd:" + pwdType);
        if ("OK".equals(res)) {
            return R.ok();
        } else {
            return R.error(ErrorCodeEnum.MINA_PUSH_ERROR);
        }
    }

}
